package com.futao.springbootlearn20220224.aware;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

/**
 * 可以获取BeanFactory，bean容器
 * 也可以使用ApplicationContext来实现一样的效果，因为ApplicationContext继承了BeanFactoryAware
 *
 * @author futao@gmail.com
 * @date 2022/3/9
 */
@Slf4j
@Component
public class BeanFactoryAwareDemo implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        log.info("可以获取到beanFactory，bean容器：{}", beanFactory);
        setBeanFactoryLocal(beanFactory);
    }

    private static void setBeanFactoryLocal(BeanFactory beanFactory) {
        BeanFactoryAwareDemo.beanFactory = beanFactory;
    }

    /**
     * 从beanFactory中获取Bean
     *
     * @param beanType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> beanType) {
        return BeanFactoryAwareDemo.beanFactory.getBean(beanType);
    }
}
